<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Car as CarModel;
use app\common\model\CarCate;
use app\common\model\Merchant as MerchatModel;
use fast\Random;
use fast\Tree;
use think\exception\ValidateException;
use think\facade\Db;
use app\common\model\MerchantCar as MerchantCarModel;

/**
 * 商家车辆管理
 *
 * @icon fa fa-circle-o
 */
class MerchantCar extends Backend
{
    
    /**
     * MerchantCar模型对象
     * @var \app\common\model\MerchantCar
     */
    protected $model = null;
    protected $merchant_id = null;

	//关联查询
	protected $relationSearch = true;
	protected $selectpageFields = 'id,car_name,car_number';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\MerchantCar;
        $this->carModel = new \app\common\model\Car();
        $merchant_id = $this->request->param('merchant_id', 0);
        $this->merchant_id = $merchant_id;

        $carList = \app\common\model\Car::getCarList(['is_delete' => 1, 'status' => 1]);

        $brandList = \app\common\model\CarCate::getColumnList(['type' => 1]);
        $configureList = \app\common\model\CarCate::getColumnList(['type' => 2]);
        $typeList = \app\common\model\CarCate::getColumnList(['type' => 3]);
        $merchantList = \app\admin\model\Merchant::field('id,merchant_name,shop_name')->where(['is_delete' => 1, 'examine_status' => 2])->select()->toArray();
        $merchantNameList = $merchantList ? array_column($merchantList, 'merchant_name', 'id') : [];
        $shopNameList = $merchantList ? array_column($merchantList, 'shop_name', 'id') : [];
        $this->view->assign(['statuslist' => $this->model->getStatusList(), 'gearlist' => CarModel::getGearList(), 'checkStatuslist' => $this->model->getCheckStatusList(), 'carStatuslist' => $this->model->getCarStatusList(), 'carList' => $carList, 'brandList' => $brandList, 'configureList' => $configureList, 'typeList' => $typeList, 'group_id' => $this->group_id, 'merchantNameList' => $merchantNameList, 'shopNameList' => $shopNameList]);
        $this->assignconfig(['statuslist' => $this->model->getStatusList(), 'gearlist' => CarModel::getGearList(), 'checkStatuslist' => $this->model->getCheckStatusList(), 'carStatuslist' => $this->model->getCarStatusList(), 'carList' => $carList, 'brandList' => $brandList, 'configureList' => $configureList, 'typeList' => $typeList, 'group_id' => $this->group_id, 'merchantNameList' => $merchantNameList, 'shopNameList' => $shopNameList]);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


	/**
	 * 查看
	 */
	public function index()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isAjax()) {
			//如果发送的来源是Selectpage，则转发到Selectpage
			if ($this->request->request('keyField')) {
				return $this->selectpage();
			}
			[$where, $sort, $order, $offset, $limit] = $this->buildparams();

			$merchantId = $this->request->param('merchant_id');
			$builder = $this->model
                ->withJoin(['car', 'merchant'])
                ->where($where);
			if($merchantId){
			    $builder->where(['merchant_car.merchant_id' => $merchantId]);
            }else{
                if($this->group_id == 2){
                    $builder->where(['merchant_car.merchant_id' => $this->merchant['id']]);
                }
            }

			$total = $builder
				->count();

			$list = $builder
				->order('merchant_car.merchant_id,merchant_car.examine_status asc,merchant_car.createtime desc')
				->limit($offset, $limit)
				->select();
            $id_list = $list->column('id');
            $car_price = \app\admin\model\MerchantCarPrice::field('merchant_car_id,count(merchant_car_id) as price_count')->where('is_delete', 1)->where('merchant_car_id', 'in', implode(',', $id_list))->group('merchant_car_id')->select()->toArray();
            $price_list = array_column($car_price, 'price_count', 'merchant_car_id');
            foreach ($list as $key=>$val){
                $list[$key]['car']['car_gear'] = CarModel::getGearList($val['car']['car_gear']);
                $list[$key]['price_count'] = $price_list[$val['id']]??0;
            }
			$result = ['total' => $total, 'rows' => $list];

			return json($result);
		}
		$params = $this->request->param();

		return $this->view->fetch();
	}

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.add' : $name) : $this->modelValidate;
                        validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
                    }

                    if(!isset($params['merchant_id'])){
                        if($this->merchant_id && $this->merchant_id != 'null'){
                            $params['merchant_id'] = $this->merchant_id;
                        }else{
                            if($this->group_id == 2){
                                $params['merchant_id'] = $this->merchant['id'];
                            }
                        }
                    }else{
                        if(!$params['merchant_id']){
                            $this->error('请选择商家');
                        }
                    }
                    if($params['merchant_id']){
                        $merchant = \app\admin\model\Merchant::where('id', $this->merchant_id)->find();
                        $params['merchant_longitude'] = $merchant['longitude']??0;
                        $params['merchant_latitude'] = $merchant['latitude']??0;
                    }
                    $car = \app\api\model\Car::where(['is_delete' => 1, 'id' => $params['car_id']])->find();
                    if(!$car){
                        Db::rollback();
                        $this->error('平台车辆不存在');
                    }
                    $params['brand_id'] = $car['brand_id'];
                    $params['model_id'] = $car['model_id'];
                    $params['type_id'] = $car['type_id'];

                    //判断车牌号唯一
                    $car_number = $params['car_number']??'';
                    if($car_number){
                        $car_find = $this->model->where(['is_delete' => 1, 'car_number' => $car_number])->count();
                        if($car_find){
                            $this->error('车牌号已存在');
                        }
                    }

                    $admin = $this->auth->getUserInfo();
                    if($admin['id'] == 1){
                        $params['examine_status'] = 2;
                    }
                    if($params['registration_time']){
                        $params['registration_time'] = strtotime($params['registration_time']);
                    }
                    $result = $this->model->save($params);
                    $merchant_car_id = $this->model->id;

                    if(isset($params['temporary_time']) && $params['temporary_time'] && $merchant_car_id){
                        $temporary_time = json_decode($params['temporary_time'], true);
                        $insert_time = [];
                        foreach ($temporary_time as $k=>$v){
                            if(!$v['start_time'] || !$v['end_time']){
                                Db::rollback();
                                $this->error('某一临时下架时间为空值');
                            }
                            $insert_time[] = [
                                'merchant_car_id' => $merchant_car_id,
                                'start_time' => strtotime($v['start_time']),
                                'end_time' => strtotime($v['end_time']),
                                'createtime' => time()
                            ];
                        }
                        if($insert_time){
                            \app\admin\model\MerchantCarTime::insertAll($insert_time);
                        }
                    }

                    if(isset($params['far_price']) && $params['far_price'] && $merchant_car_id){
                        $far_price = json_decode($params['far_price'], true);
                        $insert_price = [];
                        foreach ($far_price as $kk=>$vv){
                            if(!$vv['start_time'] || !$vv['end_time']){
                                Db::rollback();
                                $this->error('某一远期价格的时间为空值');
                            }
                            $insert_price[] = [
                                'merchant_car_id' => $merchant_car_id,
                                'start_time' => strtotime($vv['start_time']),
                                'end_time' => strtotime($vv['end_time'] . ' 23:59:59'),
                                'days' => $vv['days'],
                                'price' => $vv['price'],
                                'createtime' => time()
                            ];
                        }
                        if($insert_price){
                            \app\admin\model\MerchantCarPrice::insertAll($insert_price);
                        }
                    }

                    if(isset($params['car_insurance']) && $params['car_insurance'] && $merchant_car_id){
                        $car_insurance = json_decode($params['car_insurance'], true);
                        $insure_list  = \app\admin\model\Insure::where(['is_delete' => 1])->column('insure_name', 'id');
                        $insert_insurance = [];
                        foreach ($car_insurance as $kk=>$vv){
                            if($vv['price'] === ''){
                                Db::rollback();
                                $this->error('某一保险价格为空值');
                            }
                            $insert_insurance[] = [
                                'merchant_car_id' => $merchant_car_id,
                                'insure_id' => $vv['insure_id'],
                                'insure_name' => $insure_list[$vv['insure_id']]??'',
                                'price' => $vv['price'],
                                'createtime' => time()
                            ];
                        }
                        if($insert_insurance){
                            \app\admin\model\MerchantCarInsure::insertAll($insert_insurance);
                        }
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        //保险
        $insure = \app\admin\model\Insure::field('id as insure_id,insure_name')->where(['is_delete' => 1, 'status' => 1])->select()->toArray();
        foreach ($insure as $key=>$value){
            $insure[$key]['price'] = 0;
        }
        $car_insurance = json_encode($insure, JSON_UNESCAPED_UNICODE);
//        dump($insure);die;
        $this->view->assign('car_insurance', $car_insurance);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? $name : $this->modelValidate;
                        $pk       = $row->getPk();
                        if (!isset($params[$pk])) {
                            $params[$pk] = $row->$pk;
                        }
                        validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
                    }
                    if($row['merchant_id']){
                        $merchant = \app\admin\model\Merchant::where('id', $row['merchant_id'])->find();
                        $params['merchant_longitude'] = $merchant['longitude']??0;
                        $params['merchant_latitude'] = $merchant['latitude']??0;
                    }
                    $params['updatetime'] = time();

                    if($params['registration_time']){
                        $params['registration_time'] = strtotime($params['registration_time']);
                    }

                    $car = \app\api\model\Car::where(['is_delete' => 1, 'id' => $params['car_id']])->find();
                    if(!$car){
                        Db::rollback();
                        $this->error('平台车辆不存在');
                    }
                    $params['brand_id'] = $car['brand_id'];
                    $params['model_id'] = $car['model_id'];
                    $params['type_id'] = $car['type_id'];

                    //判断车牌号唯一
                    $car_number = $params['car_number']??'';
                    if($car_number){
                        $car_find = $this->model->where(['is_delete' => 1, 'car_number' => $car_number])->where('id', '<>', $ids)->count();
                        if($car_find){
                            $this->error('车牌号已存在');
                        }
                    }
                    $result = $row->save($params);

                    if(isset($params['temporary_time'])){
                        $old_id_list = \app\admin\model\MerchantCarTime::where(['is_delete' => 1, 'merchant_car_id' => $ids])->column('id');
                        $temporary_time = json_decode($params['temporary_time'], true);
                        $last_id_list = [];
                        $insert_time = [];
                        $update_time = [];
                        if($temporary_time){
                            foreach ($temporary_time as $k=>$v){
                                if(!$v['start_time'] || !$v['end_time']){
                                    Db::rollback();
                                    $this->error('某一临时下架时间为空值');
                                }
                                if($v['id']){
                                    $update_time[] = [
                                        'id' => $v['id'],
                                        'start_time' => strtotime($v['start_time']),
                                        'end_time' => strtotime($v['end_time']),
                                        'updatetime' => time()
                                    ];
                                    $last_id_list[] = intval($v['id']);
                                }else{
                                    $insert_time[] = [
                                        'merchant_car_id' => $ids,
                                        'start_time' => strtotime($v['start_time']),
                                        'end_time' => strtotime($v['end_time']),
                                        'createtime' => time()
                                    ];
                                }
                            }
                        }
                        $del_id_list = array_diff($old_id_list, $last_id_list);
                        if($del_id_list){
                            $res = \app\admin\model\MerchantCarTime::where(['is_delete' => 1, 'merchant_car_id' => $ids])->whereIn('id', implode(',', $del_id_list))->update(['is_delete' => 2, 'deletetime' => time()]);
                        }
                        if($insert_time){
                            \app\admin\model\MerchantCarTime::insertAll($insert_time);
                        }
                        if($update_time){
                            $time_model = new \app\admin\model\MerchantCarTime();
                            $time_model->saveAll($update_time);
                        }
                    }
                    if(isset($params['far_price'])){
                        $old_id_list = \app\admin\model\MerchantCarPrice::where(['is_delete' => 1, 'merchant_car_id' => $ids])->column('id');
                        $far_price = json_decode($params['far_price'], true);
                        $last_id_list = [];
                        $insert_price = [];
                        $update_price = [];
                        if($far_price){
                            foreach ($far_price as $kk=>$vv){
                                if(!$vv['start_time'] || !$vv['end_time']){
                                    Db::rollback();
                                    $this->error('某一远期价格的时间为空值');
                                }
                                if($vv['id']){
                                    $update_price[] = [
                                        'id' => $vv['id'],
                                        'start_time' => strtotime($vv['start_time']),
                                        'end_time' => strtotime($vv['end_time'] . ' 23:59:59'),
                                        'days' => $vv['days'],
                                        'price' => $vv['price'],
                                        'createtime' => time()
                                    ];
                                    $last_id_list[] = intval($vv['id']);
                                }else{
                                    $insert_price[] = [
                                        'merchant_car_id' => $ids,
                                        'start_time' => strtotime($vv['start_time']),
                                        'end_time' => strtotime($vv['end_time'] . ' 23:59:59'),
                                        'days' => $vv['days'],
                                        'price' => $vv['price'],
                                        'createtime' => time()
                                    ];
                                }
                            }
                        }
                        $del_id_list = array_diff($old_id_list, $last_id_list);
                        if($del_id_list){
                            \app\admin\model\MerchantCarPrice::where(['is_delete' => 1, 'merchant_car_id' => $ids])->whereIn('id', implode(',', $del_id_list))->update(['is_delete' => 2, 'deletetime' => time()]);
                        }
                        if($insert_price){
                            \app\admin\model\MerchantCarPrice::insertAll($insert_price);
                        }
                        if($update_price){
                            $price_model = new \app\admin\model\MerchantCarPrice();
                            $price_model->saveAll($update_price);
                        }
                    }
                    if(isset($params['car_insurance'])){
                        $car_insurance = json_decode($params['car_insurance'], true);
                        $insert_insurance = [];
                        $update_insurance = [];
                        $insure_list  = \app\admin\model\Insure::where(['is_delete' => 1])->column('insure_name', 'id');
                        if($car_insurance){
                            foreach ($car_insurance as $k=>$v){
                                $old_insurance = \app\admin\model\MerchantCarInsure::where(['is_delete' => 1, 'merchant_car_id' => $ids, 'insure_id' => $v['insure_id']])->find();
                                if($old_insurance){
                                    $update_insurance[] = [
                                        'id' => $old_insurance['id'],
                                        'price' => $v['price'],
                                        'insure_name' => $insure_list[$old_insurance['insure_id']]??'',
                                        'updatetime' => time()
                                    ];
                                }else{
                                    $insert_insurance[] = [
                                        'merchant_car_id' => $ids,
                                        'insure_id' => $v['insure_id'],
                                        'insure_name' => $insure_list[$v['insure_id']]??'',
                                        'price' => $v['price'],
                                        'createtime' => time()
                                    ];
                                }
                            }
                        }
                        if($insert_insurance){
                            \app\admin\model\MerchantCarInsure::insertAll($insert_insurance);
                        }
                        if($update_insurance){
                            $time_model = new \app\admin\model\MerchantCarInsure();
                            $time_model->saveAll($update_insurance);
                        }
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        //临时下架时间
        $temporary_time = \app\admin\model\MerchantCarTime::field('id,start_time,end_time')->where(['is_delete' => 1, 'merchant_car_id' => $ids])->order('createtime', 'desc')->select()->toArray();
        foreach ($temporary_time as $ke=>$va){
            $temporary_time[$ke]['start_time'] = date('Y-m-d H:i', $va['start_time']);
            $temporary_time[$ke]['end_time'] = date('Y-m-d H:i', $va['end_time']);
        }
        $temporary_time = json_encode($temporary_time, JSON_UNESCAPED_UNICODE);
        //远期价格
        $far_price = \app\admin\model\MerchantCarPrice::field('id,start_time,end_time,days,price')->where(['is_delete' => 1, 'merchant_car_id' => $ids])->order('createtime', 'desc')->select()->toArray();
        foreach ($far_price as $ky=>$vl){
            $far_price[$ky]['start_time'] = date('Y-m-d', $vl['start_time']);
            $far_price[$ky]['end_time'] = date('Y-m-d', $vl['end_time']);
        }
        $far_price = json_encode($far_price, JSON_UNESCAPED_UNICODE);
        //保险
        $insure = \app\admin\model\Insure::field('id as insure_id,insure_name')->where(['is_delete' => 1, 'status' => 1])->select()->toArray();
        $merchant_car_insurance = \app\admin\model\MerchantCarInsure::where(['is_delete' => 1, 'merchant_car_id' => $ids])->order('createtime', 'desc')->column('price', 'insure_id');
        foreach ($insure as $key=>$value){
            $insure[$key]['price'] = 0;
            if(isset($merchant_car_insurance[$value['insure_id']])){
                $insure[$key]['price'] = $merchant_car_insurance[$value['insure_id']];
            }
        }
        $car_insurance = json_encode($insure, JSON_UNESCAPED_UNICODE);
        $row['banner_list'] = explode(',', $row['banner']);
        $this->view->assign('car_insurance', $car_insurance);
        $this->view->assign('temporary_time', $temporary_time);
        $this->view->assign('far_price', $far_price);
        $this->view->assign('row', $row);

        return $this->view->fetch();
    }

    /**
     * 审核
     */
	public function check($ids){
        $row = $this->model->where('id', 'in', $ids)->select();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $examine_status = $row->column('examine_status');
        if(in_array(2, $examine_status) || in_array(3, $examine_status)){
            $this->error('有已通过或已拒绝的数据');
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
		if ($this->request->isAjax()){
			if ($this->request->isPost()){
                $params = $this->request->post('row/a');
                $status = isset($params['status']) ? $params['status'] : ($this->request->param('status') ? $this->request->param('status') : 0);
                $reason = $params['reason']??'';
                if ($status == 2 | $status == 3){

                    $result = false;
                    Db::startTrans();
                    try {
                        if($status == 3 && !$reason){
                            $this->error(__('请填写拒绝原因'));
                        }
                        $update = ['examine_status' => $status, 'examine_time' => time()];
                        if($status){
                            $update['reason'] = $reason;
                        }
                        $result = $this->model->where('id', 'in', $ids)->update($update);
                        Db::commit();
                    } catch (ValidateException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($result !== false) {
                        $this->success('审核成功');
                    } else {
                        $this->error(__('No rows were inserted'));
                    }
                }else{
                    $this->error('参数错误');
                }
			}
		}

        $this->view->assign('row', $row);

        return $this->view->fetch();
	}

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->model->where('id', 'in', $ids)->update(['is_delete' => 2, 'deletetime' => time()]);
        $this->success();
    }

    /**
     * 远期价格日历
     */
    public function far_price($ids){
        $merchant_car = \app\admin\model\MerchantCar::where(['is_delete' => 1, 'id' => $ids])->find();
        $date = $this->request->param('date', date('Y-m'));
        $last_date = date("Y-m",strtotime("last month",strtotime($date . '-' . '01')));
        $next_date = date("Y-m",strtotime("next month",strtotime($date . '-' . '01')));
        $time_date = strtotime($date);
        $merchant_price_list = \app\admin\model\MerchantCarPrice::field('id,start_time,end_time,price')->where(['is_delete' => 1, 'merchant_car_id' => $ids])->where("start_time > $time_date or end_time > $time_date")->select()->toArray();
        foreach ($merchant_price_list as &$value){
            $value['all_date'] = getDatesBetween($value['start_time'], $value['end_time']);
        }
        $list = getMonthDate($date);
        $week = ['日', '一', '二', '三', '四', '五', '六'];
        $arr1 = [];
        for($i=0;$i<$list[0]['week'];$i++){
            $arr1[] = [];
        }
        $arr2 = [];
        for($i=0;$i<(6 - end($list)['week']);$i++){
            $arr2[] = [];
        }
        foreach ($list as $k=>$v){
            $v['week'] = $week[$v['week']];
            $day = $v['date'] >= 10 ? $v['date'] : '0'.$v['date'];
            $v['price'] = $merchant_car['car_price'];
            $v['price_id'] = 0;
            $v['is_edit'] = strtotime($date . '-' . $day) > strtotime(date('Y-m-d')) ? 1 : 0;
            foreach ($merchant_price_list as $kk => $vv){
                if(in_array($date . '-' . $day, $vv['all_date'])){
                    $v['price'] = $vv['price'];
                    $v['price_id'] = $vv['id'];
                    $v['is_edit'] = 0;
                }
            }
            $list[$k] = $v;
        }
        $new_list = array_merge($arr1, $list, $arr2);
        $new_list = array_chunk($new_list, 7);
        $this->view->assign('list', $new_list);
        $this->view->assign('week', $week);
        $this->view->assign('date', $date);
        $this->view->assign('last_date', $last_date);
        $this->view->assign('next_date', $next_date);
        $this->view->assign('ids', $ids);
        return $this->view->fetch();
    }

    /**
     * 远期价格日历价格添加
     */
    public function far_price_add(){
        $price = $this->request->param('price');
        $merchant_car_id = $this->request->param('merchant_car_id');
        $date = $this->request->param('date');
        if($price === '' || $price < 0){
            $this->error('价格错误');
        }
        $merchant_car_price = \app\admin\model\MerchantCarPrice::where(['is_delete' => 1, 'merchant_car_id' => $merchant_car_id])->where('start_time', '>=', strtotime($date))->select();
        foreach ($merchant_car_price as $ke=>$vl){
            $is_time_cross = is_time_cross($vl['start_time'], $vl['end_time'], strtotime($date), strtotime($date . ' 23:59:59'));
            if($is_time_cross){
                $this->error('该日期的远期价格已存在，请重新刷新查看');
            }
        }
        $far_price = [
            'merchant_car_id' => $merchant_car_id,
            'start_time' => strtotime($date),
            'end_time' => strtotime($date . ' 23:59:59'),
            'price' => $price,
            'createtime' => time()
        ];
        $res = \app\admin\model\MerchantCarPrice::insert($far_price);
        if($res){
            $this->success('更新成功');
        }else{
            $this->error('更新失败');
        }
    }

    /**
     * Selectpage的实现方法.
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可.
     */
    public function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array) $this->request->request('q_word/a');
        //当前页
        $page = $this->request->request('pageNumber', 1, 'int');
        //分页大小
        $pagesize = $this->request->request('pageSize');
        //搜索条件
        $andor = $this->request->request('andOr', 'and', 'strtoupper');
        //排序方式
        $orderby = (array) $this->request->request('orderBy/a');
        //显示的字段
        $field = $this->request->request('showField');
        //主键
        $primarykey = $this->request->request('keyField');
        //主键值
        $primaryvalue = $this->request->request('keyValue');
        //搜索字段
        $searchfield = (array) $this->request->request('searchField/a');
        //自定义搜索条件
        $custom = (array) $this->request->request('custom/a');
        //是否返回树形结构
        $istree = $this->request->request('isTree', 0);
        $ishtml = $this->request->request('isHtml', 0);
        if ($istree) {
            $word = [];
            $pagesize = 99999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order['merchant_car.'.$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';
        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => explode(',', $primaryvalue)];
            $pagesize = null;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == ' AND ' ? ' & ' : ' | ';
//                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                if(is_array($searchfield)){
                    foreach ($searchfield as &$vv){
                        if($vv == 'car_name'){
                            $vv = 'car.' . $vv;
                        }else{
                            $vv = 'merchant_car.' . $vv;
                        }
                    }
                    $searchfield = implode($logic, $searchfield);
                }
                foreach ($word as $k => $v) {
                    $query->where(str_replace(',', $logic, $searchfield), 'like', "%{$v}%");
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            if($v[0] == 'neq'){
                                $query->where('merchant_car.' . $k, '<>', $v[1]);
                            }else{
                                $query->where('merchant_car.' . $k, trim($v[0]), $v[1]);
                            }
                        } else {
                            $query->where('merchant_car.' . $k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }

        if($this->selectpageFields){
            $selectpageFields = explode(',', $this->selectpageFields);
            foreach ($selectpageFields as &$vu){
                if($vu == 'car_name'){
                    $vu = 'car.'.$vu;
                }else{
                    $vu = 'merchant_car.' . $vu;
                }
            }
            $this->selectpageFields = implode(',', $selectpageFields);
        }
        $list = [];
        $total = $this->model->withJoin('car')->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $datalist = $this->model->withJoin('car')->where($where)
                ->order($order)
                ->page($page, $pagesize)
                ->field($this->selectpageFields)
                ->select()->toArray();
            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
//                $list[] = [
//                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
//                    $field      => isset($item[$field]) ? $item[$field] : '',
//                    'pid'       => isset($item['pid']) ? $item['pid'] : 0,
//                ];
                $item[$primarykey] = isset($item[$primarykey]) ? $item[$primarykey] : '';
                $item[$field] = isset($item[$field]) ? $item[$field] : '';
                $item['pid'] = isset($item['pid']) ? $item['pid'] : 0;
                $list[] = $item;
            }
            if ($istree && ! $primaryvalue) {
                $tree = Tree::instance();
                $tree->init($list, 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (! $ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace(' & nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }
}
